import * as React from 'react';
import { Callout } from 'office-ui-fabric-react/lib/Callout';
import { Link } from 'office-ui-fabric-react/lib/Link';
import { createRef } from 'office-ui-fabric-react/lib/Utilities';
import classnames from 'classnames';
import { SearchBox, Label, TextField, PrimaryButton, Icon } from 'office-ui-fabric-react';
import './index.less'

const dorpDown = [
  {
    "que": "共享"
  },
  {
    "que": "共享单车"
  },
  {
    "que": "共享充电宝"
  },
  {
    "que": "数据"
  },
  {
    "que": "科技"
  },
  {
    "que": "格局"
  }
]

export interface Props {
  initValue: any //初始的选项
  value: any
  options: any[]
  onChange?: any,
  onSearchChange?: any,
  onSearch?: any
  onAdvanceSearch?: any
}
export interface State {
  isDropDownVisible?: boolean;
  isCalloutVisible?: boolean;
  isActive?: boolean
  query: object
}

// Example code
export default class AdvanceSearch extends React.Component<Props, State> {
  private _menuButtonElement = createRef<HTMLElement>();

  public constructor(props: Props) {
    super(props);

    this.state = {
      isDropDownVisible: false,
      isCalloutVisible: false,
      query: props.initValue || {}
    };
  }

  private handleSearch = (): void => {
    console.info('handleSearch', this.state.query)
    // fix 去掉空值
    this.setState({
      isCalloutVisible: false
    })
    this.props.onAdvanceSearch(this.state.query)
  };
  private setActiveClass = (isActive: boolean): void => {
    this.setState({
      isActive
    })

  };
  onChange = (value) => {
    this.props.onChange(value)
    this.show()
  }
  onSearch = () => {
    this.hide()
    this.props.onSearch()
  }
  show = (e?: any) => {
    console.info('显示')
    this.stopEvent(e)
    this.setState({
      isDropDownVisible: true
    })
    document.addEventListener('click', this.handleClickOutside);
    return
  }
  hide = () => {
    this.setState({
      isDropDownVisible: false
    })
    document.removeEventListener('click', this.handleClickOutside);
  }
  handleClickOutside = (e) => {
    console.info('外部')
    this.hide()
    return
  }

  stopEvent(e) { //阻止冒泡事件
    if (e && e.stopPropagation) {
      e.stopPropagation();
      e.nativeEvent.stopImmediatePropagation();
    } else if (window.event) {
      // this code is for IE
      window.event.cancelBubble = true;
    }
  }

  selectTips = async kw => { // 选中提示搜索
    await this.props.onSearchChange(kw)
    this.props.onSearch(kw)
  }

  public render(): JSX.Element {
    const { isDropDownVisible, isCalloutVisible, isActive } = this.state;
    const { value, options = [] } = this.props
    const searchList = [1, 2]
    return (
      <div className="advance-search">
        <div className={classnames("serach-wrap", { 'isActive': isActive })} onClick={this.show}>
          <SearchBox
            placeholder="请输入关键词"
            value={value}
            onChange={this.onChange}
            onSearch={this.onSearch}
            onFocus={() => this.setActiveClass(true)}
            onBlur={() => this.setActiveClass(false)}
          />
          <div className="search-collaspe-menu" ref={this._menuButtonElement}>
            <Icon iconName="CollapseMenu" className="collapse-icon" onClick={this._onShowMenuClicked}></Icon>
          </div>
        </div>
        {
          isDropDownVisible && (
            <div className="search-down-wrap">
              <div className={classnames('search-list', { 'hide': !searchList.length })}>
                {
                  dorpDown.map(
                    (item, index) => <p key={index} role="button" className="dropdown-item" onClick={() => this.selectTips(item.que)}>{item.que}</p>
                  )
                }
              </div>
            </div>
          )
        }
        <Callout
          className="search-callout"
          ariaLabelledBy={'callout-label-1'}
          ariaDescribedBy={'callout-description-1'}
          role={'alertdialog'}
          gapSpace={0}
          target={this._menuButtonElement.value}
          onDismiss={this._onCalloutDismiss}
          setInitialFocus={true}
          hidden={!this.state.isCalloutVisible}
        >
          <div className="ms-Grid" dir="ltr">
            {options.map(
              (item, index) => {
                return (
                  <div key={index} className="ms-Grid-row option-item">
                    <div className="ms-Grid-col ms-sm4 ms-md4 ms-lg2">
                      <Label>{item.label}</Label>
                    </div>
                    <div className="ms-Grid-col ms-sm8 ms-md8 ms-lg10">
                      <TextField name={item.name}
                        placeholder="关键词"
                        value={this.state.query[item.name]}
                        onChange={(e, value) => this._onOptionChange(item.name, value)}
                      />
                    </div>
                  </div>
                )
              }
            )}
            <div className="search">
              <PrimaryButton type="submit" onSubmit={this.handleSearch} onClick={this.handleSearch}>高级检索</PrimaryButton>
            </div>
          </div>
        </Callout>
      </div>
    );
  }

  private _onOptionChange = (type, value): void => {
    console.info('_onOptionChange', type, value)
    const { query } = this.state
    query[type] = value
    this.setState({
      query
    });
  };
  private _onShowMenuClicked = (): void => {
    this.setState({
      isCalloutVisible: !this.state.isCalloutVisible,
      isDropDownVisible: false
    });
  };

  private _onCalloutDismiss = (): void => {
    this.setState({
      isCalloutVisible: false
    });
  };
}
